import React, { useCallback, useEffect, useMemo } from 'react'
import { createForm, Field, Form, onFieldValueChange } from '@formily/core'
import { ISchema, ISchemaFieldProps, createSchemaField } from '@formily/react'
import { Input, Password, FormItem } from '@formily/antd-v5'
import { usePathname } from 'next/navigation'
import { useRequest } from 'ahooks'
import { ILoginParams, login } from './request'
import { IErrorInfo } from '@/types/common'

export interface ILoginReturns {
  form: Form // 表单实例
  schema: ISchema // 表单Schema
  SchemaField: React.FC<ISchemaFieldProps> // 表单字段组件
  isLogin: boolean // 是否正在登录
  handleSubmit: () => void // 提交表单
}

export default function useLogin(): ILoginReturns {
  const pathname = usePathname()

  // 处理url，如果当前路径不是登录页，且登录页的路径不等于state中的from，就跳转到来源页
  const urlHandler = useCallback(() => {
    const state = window.history.state
    console.log(state.state)
    // 如果当前路径不是登录页，且登录页的路径不等于state中的from，就跳转到来源页
    if (pathname !== state?.from) {
      window.history.replaceState(state?.state, '', `${state?.from || '/'}${state?.search || ''}`)
      window.location.reload()
    } else {
      window.history.replaceState(state?.state, '', '/')
      window.location.reload()
    }
  }, [pathname])

  const loginForm = useMemo(
    () =>
      createForm({
        effects() {
          onFieldValueChange('*', (field: Field) => {
            field.setSelfErrors([])
          })
        }
      }),
    []
  )

  // 创建Schema
  const schema: ISchema = useMemo(() => {
    return {
      type: 'object',
      properties: {
        username: {
          type: 'string',
          title: '用户名',
          'x-decorator': 'FormItem',
          'x-decorator-props': { asterisk: true },
          'x-component': 'Input',
          'x-component-props': {
            maxLength: 20,
            placeholder: '请输入用户名',
            allowClear: true
          },
          'x-validator': (v: string) => {
            return v ? undefined : '请输入用户名'
          }
        },
        password: {
          type: 'string',
          title: '密码',
          'x-decorator': 'FormItem',
          'x-decorator-props': { asterisk: true },
          'x-component': 'Password',
          'x-component-props': {
            maxLength: 20,
            placeholder: '请输入密码',
            allowClear: true
          },
          'x-validator': (v: string) => {
            return v ? undefined : '请输入密码'
          }
        }
      }
    }
  }, [])

  const SchemaField = useMemo(() => createSchemaField({ components: { Input, Password, FormItem } }), [])

  const { loading: isLogin = false, run: handleSubmit } = useRequest(
    async () => {
      const values: ILoginParams = await loginForm.submit()
      const res = await login(values)
      const { data, success } = res
      if (!success) {
        if (Array.isArray((data as IErrorInfo)?.data)) {
          ;(data as IErrorInfo).data?.forEach(item => {
            loginForm.setFieldState(item.field, { selfErrors: [item.message] })
          })
        }
      } else if (data) {
        localStorage.setItem('user-token', data as string)
        urlHandler()
      }
    },
    { manual: true, refreshDeps: [loginForm] }
  )

  useEffect(() => {
    const token = localStorage.getItem('user-token')
    if (token) {
      urlHandler()
    }
  }, [urlHandler])

  return { isLogin, handleSubmit, form: loginForm, schema, SchemaField }
}
